
package com.dyzx.hbb.common.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyzx.hbb.common.constant.InitConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashSet;
import java.util.List;

/**
 * 分页查询基础类
 */
@Data
@Schema(description = "分页查询参数")
public class PageQuery {

    /**
     * 当前页码
     */
    @Schema(description = "当前页码", example = "1")

    @JsonProperty("page")
    private Integer page = 1;

    /**
     * 每页数量
     */
    @Schema(description = "每页数量", example = "10")

    @JsonProperty("page_size")
    private Integer page_size = 10;

    /**
     * 排序字段
     */
    @Schema(description = "排序字段")
    private String sort;

    /**
     * 排序方式：asc/desc
     */
/*    @Schema(description = "排序方式：asc/desc")
    private String orderType;*/
    /**
     * 转换为MyBatis-Plus的Page对象
     *
     * @param <T> 实体类型
     * @return Page<T>
     */
    public <T> Page<T> toPage() {
        Page<T> pageI = new Page<>(page, page_size);
     if (StringUtils.isNotBlank(sort)) {
         String requestURI = InitConfig.getRequest().getRequestURI();
         JSONObject sortInit = InitConfig.getSort();
         if (sortInit != null) {
             System.out.println("sortInit:");
             System.out.println(requestURI);
             System.out.println(sortInit);
             if (sortInit.containsKey(requestURI)) {

                 JSONArray jsonArray = sortInit.getJSONArray(requestURI);
                 List<String> javaList = jsonArray.toJavaList(String.class);
                 // javaList.contains(sort)

                 String[] split = sort.split(",");
                 for (String s : split) {
                     String[] split1 = s.split(":");
                     String column = split1[0];
                     if (javaList.contains(column)) {
                         OrderItem orderItem = new OrderItem();
                         orderItem.setColumn(column);

                         boolean asc = "asc".equalsIgnoreCase(split1[1]);
                      //   boolean desc = "desc".equalsIgnoreCase(split1[1]);

                             orderItem.setAsc(asc);



                         orderItem.setAsc("asc".equalsIgnoreCase(split1[1]));

                         pageI.addOrder(orderItem);
                     }
                 }

             }
         }
     }else {

         pageI.addOrder(OrderItem.desc("id"));


     }
        return pageI;
    }
}